//! # 组件工厂实现
//! 
//! 本模块提供了组件工厂的实现，包括简单工厂和便捷宏。

use crate::di::traits::*;
use rustcloud_core::{ServiceResult, ServiceError};
use std::any::{Any, TypeId};
use std::sync::Arc;
use async_trait::async_trait;

/// 简单工厂实现
pub struct SimpleFactory<T, F>
where
    T: 'static,
    F: Fn(&dyn Container) -> std::pin::Pin<Box<dyn std::future::Future<Output = ServiceResult<Arc<T>>> + Send>> + Send + Sync,
{
    factory_fn: F,
    dependencies: Vec<TypeId>,
    _phantom: std::marker::PhantomData<T>,
}

impl<T, F> SimpleFactory<T, F>
where
    F: Fn(&dyn Container) -> std::pin::Pin<Box<dyn std::future::Future<Output = ServiceResult<Arc<T>>> + Send>> + Send + Sync,
{
    pub fn new(factory_fn: F) -> Self {
        Self {
            factory_fn,
            dependencies: Vec::new(),
            _phantom: std::marker::PhantomData,
        }
    }

    pub fn with_dependencies(mut self, dependencies: Vec<TypeId>) -> Self {
        self.dependencies = dependencies;
        self
    }
}

#[async_trait]
impl<T, F> ComponentFactory<T> for SimpleFactory<T, F>
where
    T: 'static,
    F: Fn(&dyn Container) -> std::pin::Pin<Box<dyn std::future::Future<Output = ServiceResult<Arc<T>>> + Send>> + Send + Sync,
{
    async fn create(&self, container: &dyn Container) -> ServiceResult<Arc<T>> {
        (self.factory_fn)(container).await
    }

    fn dependencies(&self) -> Vec<TypeId> {
        self.dependencies.clone()
    }
}

/// 便捷宏：注册单例组件
#[macro_export]
macro_rules! register_singleton {
    ($container:expr, $name:expr, $type:ty, $factory:expr) => {
        $container.register_singleton::<$type>($name, SimpleFactory::new($factory)).await
    };
}

/// 便捷宏：注册瞬态组件
#[macro_export]
macro_rules! register_transient {
    ($container:expr, $name:expr, $type:ty, $factory:expr) => {
        $container.register_transient::<$type>($name, SimpleFactory::new($factory)).await
    };
}